package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"yanxue_ai_go/pkg/common/config"
	"yanxue_ai_go/pkg/common/initialize"
	"yanxue_ai_go/pkg/common/logger"
	"yanxue_ai_go/pkg/common/middleware"
	"yanxue_ai_go/services/agent/internal/handler"
	"yanxue_ai_go/services/agent/internal/service"
)

func main() {
	// 初始化服务依赖
	initResult, err := initialize.InitializeService("agent")
	if err != nil {
		logger.Logger.Fatal("Failed to initialize service", zap.Error(err))
	}
	defer initResult.Cleanup()

	// 初始化服务
	agentService := service.NewAgentService()

	// 初始化AI服务
	aiService, err := service.NewAIService(initResult.Config)
	if err != nil {
		logger.Logger.Fatal("Failed to initialize AI service", zap.Error(err))
	}

	// 初始化路由
	router := setupRouter(initResult.Config, agentService, aiService)

	// 启动服务器
	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", 8081),
		Handler:      router,
		ReadTimeout:  time.Duration(initResult.Config.Server.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(initResult.Config.Server.WriteTimeout) * time.Second,
		IdleTimeout:  time.Duration(initResult.Config.Server.IdleTimeout) * time.Second,
	}

	// 启动服务器并等待关闭信号
	go func() {
		logger.Logger.Info("Agent service started",
			zap.String("addr", server.Addr),
			zap.String("env", initResult.Config.App.Environment))

		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Logger.Fatal("Failed to start server", zap.Error(err))
		}
	}()

	// 优雅关闭
	shutdownHandler := initialize.NewGracefulShutdown("agent", server, initResult.Cleanup)
	if err := shutdownHandler.Wait(); err != nil {
		logger.Logger.Error("Shutdown error", zap.Error(err))
	}
}

func setupRouter(cfg *config.Config, agentService *service.AgentService, aiService *service.AIService) *gin.Engine {
	if cfg.App.Environment == "production" {
		gin.SetMode(gin.ReleaseMode)
	}

	router := gin.New()

	// 添加中间件
	router.Use(middleware.LoggerMiddleware())
	router.Use(middleware.RecoveryMiddleware())
	router.Use(middleware.CORSMiddleware(
		cfg.Security.CORSAllowedOrigins,
		cfg.Security.CORSAllowedMethods,
		cfg.Security.CORSAllowedHeaders,
	))

	// 健康检查
	router.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "healthy", "service": "agent"})
	})

	// API路由
	h := handler.NewAgentHandler(agentService)
	chatHandler := handler.NewChatHandler()
	knowledgeHandler := handler.NewKnowledgeHandler(aiService)

	api := router.Group("/api/v1")
	{
		// AI问答路由
		chat := api.Group("/chat")
		{
			chat.POST("/ask", chatHandler.Chat)
			chat.GET("/config", chatHandler.GetConfig)
		}

		// 知识百科Agent路由
		knowledge := api.Group("/knowledge")
		{
			// Agent管理
			knowledge.POST("/agents", knowledgeHandler.CreateKnowledgeAgent)
			knowledge.GET("/agents/:id", knowledgeHandler.GetKnowledgeAgentInfo)
			knowledge.GET("/agents/:id/analytics", knowledgeHandler.GetKnowledgeAnalytics)

			// 会话管理
			knowledge.POST("/agents/:id/session", knowledgeHandler.StartKnowledgeSession)

			// 问答功能
			knowledge.POST("/agents/:id/ask", knowledgeHandler.QuickAsk)
			knowledge.POST("/ask", knowledgeHandler.AskQuestion)
			knowledge.GET("/history", knowledgeHandler.GetKnowledgeHistory)
			knowledge.POST("/rate", knowledgeHandler.RateAnswer)

			// 辅助功能
			knowledge.GET("/categories", knowledgeHandler.GetKnowledgeCategories)
			knowledge.GET("/agents/:id/popular", knowledgeHandler.GetPopularQuestions)
		}

		// Agent相关路由
		agents := api.Group("/agents")
		{
			agents.POST("", h.CreateAgent)
			agents.GET("", h.ListAgents)
			agents.GET("/:id", h.GetAgent)
			agents.PUT("/:id", h.UpdateAgent)
			agents.DELETE("/:id", h.DeleteAgent)
			agents.POST("/:id/execute", h.ExecuteAgent)
			agents.GET("/:id/status", h.GetAgentStatus)
		}

		tasks := api.Group("/tasks")
		{
			tasks.POST("", h.CreateTask)
			tasks.GET("", h.ListTasks)
			tasks.GET("/:id", h.GetTask)
			tasks.PUT("/:id", h.UpdateTask)
			tasks.DELETE("/:id", h.DeleteTask)
		}
	}

	return router
}
